package org.huang.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * @author hdu_huang
 * @since 2024/1/10 16:00
 */

@Configuration
//@MapperScan("com.client.dao")
//@EnableTransactionManagement
@EnableScheduling
@EnableAsync
@ServletComponentScan
@EnableCaching
@Slf4j
public class BeanConfig implements ApplicationContextAware {

    @Getter
    private static ApplicationContext context;

    //暴露 ApplicationContext
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    //@Bean
    //public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
    //    RedisTemplate<String, Serializable> template = new RedisTemplate<>();
    //    template.setKeySerializer(new StringRedisSerializer());
    //    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    //    template.setConnectionFactory(redisConnectionFactory);
    //    return template;
    //}

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(3000);
        factory.setConnectTimeout(3000);
        return factory;
    }

    //Spring 生在代理类时[通过 ReflectionFactory 创造无参构造器实例化]
    //ObjenesisCglibAopProxy(SpringObjenesis) -> ReflectionFactory.newConstructorForSerialization
    @Bean
    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }


}
